'use strict'

class content {

  constructor() {
    //param默认就是/:id，若要改变路由，则可以设置此属性，比如设置为/:name
    //this.param = '/:id'
  }

  //以下方法，若不需要，要去掉，避免无意义的路由。

  //获取资源具体内容
  //对应路由 GET /content/:id
  async get(c) {
    let sqltext = `SELECT * FROM content WHERE id=$1`

    let r = await c.service.psql.query(sqltext, [c.param.id])

    if (r.rowCount == 0) { //rowCount是指获取了多少条id,当等于0则没有获取到
      return c.status(404).send('content not found')
    }

    c.send(r.rows[0])//rows是数组
  }

  //创建资源
  //对应路由 POST /content
  async post(c) {
    try {
      /**
       * text/json c.body转换成字符串类型
       */
      //提交的Body数据通过c.body获取
      let data = JSON.parse(c.body)

      let sqltext = `INSERT INTO `
        + ` content(id, add_time, detail, title, update_time) `
        + ` VALUES ($1, $2, $3, $4, $5)`

      //生成唯一ID
      let id = c.helper.makeId() //随机生成
      let tm = Date.now()

      let r = await c.service.psql.query(sqltext, [
        id, tm, data.detail, data.title, tm //对应上面的$1-$5
      ])

      if (r.rowCount === 0) {
        return c.status(500).send('failed')
      }

      c.send(id)

    } catch (err) {
      c.status(400).send('it is not json data')
    }
  }

  //更新资源
  //对应路由 PUT /content/:id
  async put(c) {

  }

  //获取列表
  //对应路由 GET /content
  async list(c) {
    let ret = await c.service.psql.query(`select * from content`)
    //等效于 c.res.body = ret.rows
    c.send(ret.rows) // rows是每一个数据

  }

  //删除资源
  //对应路由 DELETE /content/:id
  async delete(c) {
    let sqltext = `DELETE FROM content WHERE id=$1`

    let r = await c.service.psql.query(sqltext, [c.param.id])

    if (r.rowCount == 0) { //rowCount是指获取了多少条id,当等于0则没有获取到
      return c.status(404).send('content not found')
    }

    c.send(r.rows[0])//rows是数组

  }

  __mid(){ //对post,delete请求启动中间件
    return [
      {
        name: 'token-verify',
        path: ['post','delete']
      }
    ]

  }

}

module.exports = content
